#include "preHeader.h"
#include "FuncUtils.h"

void LoadConfigByFormat(const char* fmt, char* ptr, TextUnpacker& unpacker)
{
	for (; *fmt != '\0'; ++fmt) {
		switch (*fmt) {
		case 'f':
			*(f32*)ptr = unpacker.Unpack<f32>();
			ptr += sizeof(f32);
			break;
		case 'i':
			*(s32*)ptr = unpacker.Unpack<s32>();
			ptr += sizeof(s32);
			break;
		case 'u':
			*(u32*)ptr = unpacker.Unpack<u32>();
			ptr += sizeof(u32);
			break;
		default:
			assert(false && "can't reach here.");
			break;
		}
	}
}

std::string StrPrintf(const char* fmt, ...)
{
	std::string str;
	va_list ap;
	va_start(ap, fmt);
	str.resize(vsnprintf(NULL, 0, fmt, ap) + 1);
	va_end(ap);
	va_start(ap, fmt);
	str.resize(vsnprintf(&str[0], str.size(), fmt, ap));
	va_end(ap);
	return str;
}

bool IsKeyInString(const std::string_view& str, const std::string_view& key, char delimiter)
{
	size_t i = 0;
	while (true) {
		if (str.size() < key.size() + i) {
			return false;
		}
		if ((str.compare(i, key.size(), key.data()) == 0) &&
			(str.size() == key.size() + i || str[key.size() + i] == delimiter)) {
			return true;
		}
		if ((i = str.find_first_of(delimiter, i)) != std::string_view::npos) {
			++i;
		} else {
			break;
		}
	}
	return false;
}

bool IsKeyValueInRangeString(const std::string& str, int key)
{
	TextUnpacker unpacker(str.c_str());
	while (!unpacker.IsEmpty()) {
		int valMin = unpacker.Unpack<int>();
		if (!unpacker.IsEmpty() && unpacker.IsDelimiter('-')) {
			int valMax = unpacker.Unpack<int>();
			if (IsInRange(key, valMin, valMax)) {
				return true;
			}
		} else {
			if (key == valMin) {
				return true;
			}
		}
	}
	return false;
}
